package com.atguigu.yygh.msm.controller;


import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/send/{phone}")
    public Result code(@PathVariable String phone){
        //设置在有效时间内不能再次发送
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return Result.ok();

        //生成验证码
         code = RandomUtil.getFourBitRandom();


        boolean isSuccess = msmService.sendCode(phone,code);

        //放到redis中 设置过期时间
        if (isSuccess){
            redisTemplate.opsForValue().set(phone,code,60, TimeUnit.MINUTES);
        }
        return Result.ok();
    }
}
